<template>
  <view class="file-list-container">
    <view class="header-section">
      <text class="page-title">文件管理</text>
    </view>
    
    <view class="toolbar-section">
      <button class="action-button" @click="showUploadModal">上传文件</button>
    </view>
    
    <view class="file-list">
      <view class="file-item" v-for="file in fileList" :key="file.id">
        <view class="file-info">
          <text class="file-name">{{ file.name }}</text>
          <text class="file-size">{{ formatFileSize(file.size) }}</text>
          <text class="file-time">{{ formatTime(file.createdAt) }}</text>
        </view>
        <view class="file-actions">
          <button class="action-button small" @click="downloadFile(file)">下载</button>
          <button class="action-button small danger" @click="deleteFile(file)">删除</button>
        </view>
      </view>
    </view>
    
    <view class="pagination-section">
      <button class="pagination-button" :disabled="currentPage <= 1" @click="prevPage">上一页</button>
      <text class="page-info">第 {{ currentPage }} 页，共 {{ totalPages }} 页</text>
      <button class="pagination-button" :disabled="currentPage >= totalPages" @click="nextPage">下一页</button>
    </view>
    
    <view class="empty-state" v-if="fileList.length === 0">
      <text class="empty-text">暂无文件</text>
    </view>
    
    <!-- 上传文件弹窗 -->
    <view class="modal" v-if="showUploadModalFlag">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">上传文件</text>
          <button class="close-button" @click="closeUploadModal">×</button>
        </view>
        <view class="modal-body">
          <view class="form-item">
            <text class="form-label">选择文件</text>
            <button class="file-upload-button" @click="selectFile">选择文件</button>
            <text class="file-name" v-if="selectedFile">{{ selectedFile.name }}</text>
          </view>
          <view class="form-item">
            <text class="form-label">文件描述</text>
            <textarea class="form-textarea" v-model="fileDescription" placeholder="请输入文件描述"></textarea>
          </view>
        </view>
        <view class="modal-footer">
          <button class="action-button cancel" @click="closeUploadModal">取消</button>
          <button class="action-button" @click="uploadFile" :disabled="!selectedFile">上传</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { fileApi } from '../../../src/services/system'

// 文件列表
const fileList = ref<any[]>([])

// 分页信息
const currentPage = ref(1)
const pageSize = ref(10)
const totalPages = ref(1)
const totalFiles = ref(0)

// 是否显示上传文件弹窗
const showUploadModalFlag = ref(false)

// 选中的文件
const selectedFile = ref<File | null>(null)

// 文件描述
const fileDescription = ref('')

// 页面加载时获取文件列表
onMounted(() => {
  fetchFileList()
})

// 获取文件列表
const fetchFileList = async () => {
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    const response: any = await fileApi.getFileList(params)
    fileList.value = response.data.list || response.data
    totalFiles.value = response.data.total || fileList.value.length
    totalPages.value = Math.ceil(totalFiles.value / pageSize.value)
    
    uni.showToast({
      title: '获取文件列表成功',
      icon: 'success'
    })
  } catch (error) {
    console.error('获取文件列表失败:', error)
    uni.showToast({
      title: '获取文件列表失败',
      icon: 'none'
    })
  }
}

// 显示上传文件弹窗
const showUploadModal = () => {
  showUploadModalFlag.value = true
  selectedFile.value = null
  fileDescription.value = ''
}

// 关闭上传文件弹窗
const closeUploadModal = () => {
  showUploadModalFlag.value = false
}

// 选择文件
const selectFile = () => {
  // 在实际应用中，这里会调用文件选择器
  uni.showToast({
    title: '文件选择功能开发中',
    icon: 'none'
  })
}

// 上传文件
const uploadFile = async () => {
  if (!selectedFile.value) {
    uni.showToast({
      title: '请选择文件',
      icon: 'none'
    })
    return
  }
  
  try {
    uni.showLoading({
      title: '上传中...'
    })
    
    // 这里应该调用文件上传API
    // const formData = new FormData()
    // formData.append('file', selectedFile.value)
    // formData.append('description', fileDescription.value)
    // await fileApi.uploadFile(formData)
    
    uni.hideLoading()
    uni.showToast({
      title: '上传文件成功',
      icon: 'success'
    })
    
    // 关闭弹窗
    closeUploadModal()
    
    // 重新获取文件列表
    fetchFileList()
  } catch (error) {
    uni.hideLoading()
    console.error('上传文件失败:', error)
    uni.showToast({
      title: '上传文件失败',
      icon: 'none'
    })
  }
}

// 下载文件
const downloadFile = async (file: any) => {
  try {
    uni.showLoading({
      title: '下载中...'
    })
    
    // 这里应该调用文件下载API
    // const response = await fileApi.downloadFile(file.id)
    // 处理文件下载逻辑
    
    uni.hideLoading()
    uni.showToast({
      title: '文件下载成功',
      icon: 'success'
    })
  } catch (error) {
    uni.hideLoading()
    console.error('下载文件失败:', error)
    uni.showToast({
      title: '下载文件失败',
      icon: 'none'
    })
  }
}

// 删除文件
const deleteFile = async (file: any) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除文件 "${file.name}" 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await fileApi.deleteFile(file.id)
          
          uni.showToast({
            title: '删除文件成功',
            icon: 'success'
          })
          
          // 重新获取文件列表
          fetchFileList()
        } catch (error) {
          console.error('删除文件失败:', error)
          uni.showToast({
            title: '删除文件失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB'
  } else {
    return (size / (1024 * 1024)).toFixed(2) + ' MB'
  }
}

// 格式化时间
const formatTime = (time: string) => {
  return time ? time.split('T')[0] : ''
}

// 上一页
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    fetchFileList()
  }
}

// 下一页
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    fetchFileList()
  }
}
</script>

<style lang="scss" scoped>
.file-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20rpx;
}

.header-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  
  .page-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    text-align: center;
  }
}

.toolbar-section {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  text-align: right;
}

.action-button {
  background-color: #4B0082;
  color: #fff;
  border: none;
  padding: 15rpx 30rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  
  &.small {
    padding: 10rpx 20rpx;
    font-size: 24rpx;
  }
  
  &.danger {
    background-color: #f44336;
  }
  
  &.cancel {
    background-color: #999;
  }
  
  &:disabled {
    background-color: #ccc;
  }
}

.file-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.file-item {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.file-info {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  margin-bottom: 20rpx;
}

.file-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.file-size {
  font-size: 28rpx;
  color: #4B0082;
}

.file-time {
  font-size: 24rpx;
  color: #999;
}

.file-actions {
  display: flex;
  gap: 10rpx;
  justify-content: flex-end;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30rpx;
  padding: 0 20rpx;
}

.pagination-button {
  background-color: #4B0082;
  color: #fff;
  border: none;
  padding: 10rpx 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.pagination-button[disabled] {
  background-color: #ccc;
}

.page-info {
  font-size: 28rpx;
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 10rpx;
  width: 90%;
  max-width: 600rpx;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 2rpx solid #f5f5f5;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-button {
  background: none;
  border: none;
  font-size: 40rpx;
  color: #999;
  padding: 0;
  width: 50rpx;
  height: 50rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-body {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.form-item {
  margin-bottom: 30rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.file-upload-button {
  background-color: #f5f5f5;
  border: 2rpx dashed #ccc;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  color: #666;
  width: 100%;
  text-align: center;
}

.file-name {
  display: block;
  font-size: 24rpx;
  color: #4B0082;
  margin-top: 10rpx;
}

.form-textarea {
  background-color: #f5f5f5;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  width: 100%;
  height: 150rpx;
  box-sizing: border-box;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
  padding: 30rpx;
  border-top: 2rpx solid #f5f5f5;
}
</style>